package com.help10000.rms.ui.fragments

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import com.amir.common.api.ApiContents
import com.amir.common.beans.AppVersionInfoEntity
import com.amir.common.beans.BaseResult
import com.amir.common.beans.CompanyEntity
import com.amir.common.beans.LogOffResult
import com.amir.common.beans.TempleteInfo
import com.amir.common.beans.UserInfo
import com.amir.common.beans.UserInfoData
import com.amir.common.utils.Constant
import com.amir.common.utils.DisplayUtil
import com.amir.common.utils.ImageHelper
import com.amir.common.utils.LogUtils
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.weight.DuplicateClickProxy
import com.help10000.rms.R
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.presenter.AppVersionInfoPresenter
import com.help10000.rms.mvp.presenter.CompanyListPresenter
import com.help10000.rms.mvp.presenter.SelectCompanyPresenter
import com.help10000.rms.mvp.presenter.UserInfoPresenter
import com.help10000.rms.mvp.view.CommonView
import com.help10000.rms.mvp.view.CompanyListView
import com.help10000.rms.mvp.view.SelectCompanyView
import com.help10000.rms.mvp.view.UserInfoView
import com.help10000.rms.ui.activitys.BindEmployeeActivity
import com.help10000.rms.ui.activitys.OpenUrlActivity
import com.help10000.rms.ui.activitys.SelectCompanyActivity
import com.help10000.rms.ui.activitys.logins.LoginActivity
import com.help10000.rms.ui.activitys.mine.AppVersionInfoActivity
import com.help10000.rms.ui.activitys.mine.address.AddressActivity
import com.help10000.rms.ui.activitys.mine.feedback.FeedBackListActivity
import com.help10000.rms.ui.activitys.mine.user_info.UserInfoActivity
import com.help10000.rms.ui.base.BaseFragment
import com.help10000.rms.ui.utils.PageUtils
import com.help10000.rms.ui.windows.SharePopu
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fragment_mine.cacheSizeTextView
import kotlinx.android.synthetic.main.fragment_mine.feedBackMsgState
import kotlinx.android.synthetic.main.fragment_mine.header
import kotlinx.android.synthetic.main.fragment_mine.iv_head
import kotlinx.android.synthetic.main.fragment_mine.ll_about
import kotlinx.android.synthetic.main.fragment_mine.ll_address
import kotlinx.android.synthetic.main.fragment_mine.ll_advise
import kotlinx.android.synthetic.main.fragment_mine.ll_cache
import kotlinx.android.synthetic.main.fragment_mine.ll_contact
import kotlinx.android.synthetic.main.fragment_mine.ll_exit
import kotlinx.android.synthetic.main.fragment_mine.ll_selectcompany
import kotlinx.android.synthetic.main.fragment_mine.ll_share
import kotlinx.android.synthetic.main.fragment_mine.ll_update
import kotlinx.android.synthetic.main.fragment_mine.ll_wallet
import kotlinx.android.synthetic.main.fragment_mine.newVersionState
import kotlinx.android.synthetic.main.fragment_mine.newVersionTextView
import kotlinx.android.synthetic.main.fragment_mine.serviceTellTextView
import kotlinx.android.synthetic.main.fragment_mine.switchCmpyTextView
import kotlinx.android.synthetic.main.fragment_mine.tv_cmpy
import kotlinx.android.synthetic.main.fragment_mine.tv_id
import kotlinx.android.synthetic.main.fragment_mine.tv_name
import kotlinx.android.synthetic.main.fragment_mine.userInfoLayout
import java.io.File


class MineFragment : BaseFragment<UserInfoPresenter, UserInfoView>(),
    View.OnClickListener,
    CompanyListView, UserInfoView, CommonView<AppVersionInfoEntity>, SelectCompanyView {

    var companyListPresenter = CompanyListPresenter(this)
    var checkUpdatePresenter = AppVersionInfoPresenter(this)
    var cmpyCode = globalData.Cmpy?.CmpyCode;
    var shareInfo: TempleteInfo? = null;

    companion object {
        @JvmStatic
        fun newInstance() =
            MineFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
    override fun onLogOffSuccess(result: LogOffResult) {
        ToastUtil.show("账号注销成功")
    }
    // 注意：如果 UserInfoView 还有其他抽象函数（比如之前的 onLogOffFailure、userInfoSucc 等），
    // 也必须一起补全实现，否则会报同样的“未实现抽象成员”错误！
    // 示例：补全其他可能遗漏的抽象函数
    override fun onLogOffFailure(message: String) {
        ToastUtil.show(message) // 注销失败的提示逻辑
    }


    override fun getlayoutId(): Int {
        return R.layout.fragment_mine
    }

    override fun initView(rootView: View?) {
        header.setPadding(0, DisplayUtil.getStatusBarHeight(mContext), 0, 0)
    }

    override fun lazyLoad() {
        if (globalData.userInfo != null) {
            initUserInfo(globalData.userInfo!!)
        } else {
            mPresenter.initUserInfo()
            //检查更新
            checkUpdatePresenter.checkUpdate()
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun initListener() {
        ll_share.setOnClickListener(DuplicateClickProxy(this))
        ll_selectcompany.setOnClickListener(DuplicateClickProxy(this))
        ll_update.setOnClickListener(DuplicateClickProxy(this))
        ll_exit.setOnClickListener(DuplicateClickProxy(this))
        ll_address.setOnClickListener(DuplicateClickProxy(this))
        ll_advise.setOnClickListener(DuplicateClickProxy(this))
        ll_about.setOnClickListener(DuplicateClickProxy(this))
        ll_cache.setOnClickListener(DuplicateClickProxy(this))
        ll_wallet.setOnClickListener(DuplicateClickProxy(this))
        userInfoLayout.setOnClickListener(DuplicateClickProxy(this))
        iv_head.setOnClickListener(DuplicateClickProxy(this))
        switchCmpyTextView.setOnClickListener(DuplicateClickProxy(this))
        ll_contact.setOnClickListener(DuplicateClickProxy(this))

        var totalSize = getDirectorySize(requireContext().externalCacheDir)
        if (totalSize == 0L)
            cacheSizeTextView.text = "0M"
        else
            cacheSizeTextView.text = String.format("%.1fM", (totalSize / (1024 * 1024.0f)));


    }

    fun clearDirectory(file: File?) {
        var files = file?.listFiles()
        if (files == null) {
            file?.delete()
            return
        }
        for (fi in files) {
            if (fi.isFile)
                fi.delete();
            else
                clearDirectory(fi);
        }
    }

    fun getDirectorySize(file: File?): Long {
        var files = file?.listFiles()
        if (files == null)
            return 0L;
        var fileSize = 0L;
        for (fi in files) {
            if (fi.isFile)
                fileSize += fi.length();
            else
                fileSize += getDirectorySize(fi);
        }
        return fileSize;
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_head,
            R.id.userInfoLayout -> {
                startActivity(Intent(mContext, UserInfoActivity::class.java))
            }
            R.id.ll_address -> {
                startActivity(Intent(mContext, AddressActivity::class.java))
            }
            R.id.ll_about -> {
                OpenUrlActivity.startActivity(mContext, mPresenter.getAboutUrl())
            }
            R.id.ll_advise -> {
                startActivity(Intent(mContext, FeedBackListActivity::class.java))
            }
            R.id.ll_share -> {
                SharePopu(mContext, R.layout.popu_share, shareInfo)
                    .showAtLocation(ll_share, Gravity.BOTTOM, 0, 0)
            }
            R.id.ll_update -> {
                PageUtils.jumpToActivity(mContext, AppVersionInfoActivity::class.java)

            }
            R.id.ll_selectcompany -> {
                val companyListPresenter = CompanyListPresenter(this)
                companyListPresenter.companyList()
            }
            R.id.ll_exit -> {
                XPopup.Builder(getViewContext())
                    .asConfirm(
                        null, "登出后，您将不能接收来自公司或者客户的消息通知"
                    ) {
                        SPUtils.remove(Constant.CmpyCode)
                        SPUtils.remove(Constant.pwd)
                        SPUtils.remove(Constant.accountName)
                        SPUtils.remove(Constant.encodePassword)
                        SPUtils.remove(Constant.nonceStr)
                        SPUtils.remove(Constant.read_privacy)
                        mPresenter.loginOut()

                    }.show()
            }
            R.id.ll_contact -> {
                if (serviceTellTextView.text.isNullOrEmpty())
                    return
                val phoneIntent = Intent(Intent.ACTION_DIAL)
                phoneIntent.data = Uri.parse("tel:" + serviceTellTextView.text)
                try {
                    startActivity(phoneIntent)
                } catch (ex: ActivityNotFoundException) {
                    ToastUtil.show("拨打电话失败")
                }
            }
            R.id.ll_cache -> {
                cacheSizeTextView.text = "0M"
                clearDirectory(requireContext().externalCacheDir);
                ToastUtil.show("缓存已清理")
            }
            R.id.ll_wallet -> {
                //PageUtils.jumpToActivity(mContext, WalletDetailActivity::class.java)
                val intent = Intent("com.action.menu.to_wallet")
                activity?.sendBroadcast(intent)
                LogUtils.I("TrackMenu ll_wallet sendBroadcast")
            }
            R.id.switchCmpyTextView -> {
                companyListPresenter?.companyList()
            }

        }
    }

    override fun showLoading() {

    }

    override fun onResume() {
        super.onResume()

        cmpyCode = globalData.Cmpy?.CmpyCode;
        mPresenter.initUserInfo()

    }

    override fun companyLoginSuccess() {
        cmpyCode = globalData.Cmpy?.CmpyCode;
        mPresenter.initUserInfo()
    }

    override fun companyListData(t: CompanyEntity) {
        /**
         * 跳转公司
         */
        if (t.data.CmpyList.size == 1) {
            var selectCompanyPresenter = SelectCompanyPresenter(this)
            selectCompanyPresenter.companyLogin(t.data.CmpyList[0])
        } else if (t.data.CmpyList.size > 1) {
            val intent = Intent(mContext, SelectCompanyActivity::class.java)
            intent.putExtra("data", t.data)
            intent.putExtra("flag", 1)
            startActivity(intent)
        } else {
            /**
             * 跳转员工
             */
            startActivity(Intent(mContext, BindEmployeeActivity::class.java))
        }


    }

    fun initUserInfo(user: UserInfo) {
        if (!user.UserLogo.isNullOrEmpty()) {
            LogUtils.E("${ApiContents.ImageUrl}${user.UserLogo}")
            ImageHelper.displayCircleImage(
                mContext,
                "${ApiContents.ImageUrl}${user.UserLogo}",
                iv_head
            )
        }
        tv_name.text = "${user.UserName}"
        tv_id.text = "ID:${user.AccountId}"
        tv_cmpy.text = globalData.Cmpy?.CmpyName

    }

    override fun userInfoSucc(t: UserInfoData) {
        initUserInfo(t.UserInfo)
        switchCmpyTextView.visibility = if (t.ShowSwitch) View.VISIBLE else View.GONE;
        feedBackMsgState.visibility =
            if (t.Feelback.FeelbackReply_NoReadQty > 0) View.VISIBLE else View.GONE;
        serviceTellTextView.text = t.TempleteInfo?.ServiceTel;
        this.shareInfo = t.TempleteInfo
    }

    override fun loginOutSuccess(t: BaseResult) {
        PageUtils.jumpToActivity(mContext, LoginActivity::class.java)
        activity?.finish()
    }

    override fun onAvatarUpload(fileUrl: String) {
        mPresenter.updateAvatar(fileUrl)
    }

    override fun onAvatarUpdateSuccess() {
        ToastUtil.show("头像修改成功")
        mPresenter.initUserInfo()
    }

    override fun createPresenter(): UserInfoPresenter {
        return UserInfoPresenter(this)
    }

    override fun onDataSuccess(data: AppVersionInfoEntity) {
        var versionCode =
            getViewContext()?.packageManager?.getPackageInfo(
                getViewContext()!!.packageName,
                0
            )?.versionCode
        if (data.data!!.AppVersionInfo!!.Id > versionCode!!) {
            Log.d("本地", "$versionCode")
            newVersionTextView.text = data.data!!.AppVersionInfo!!.Version
            var a=data.data!!.AppVersionInfo!!.Id
            Log.d("远程服务端", "$a")
            newVersionState.visibility = View.VISIBLE
        }
    }

}

